//
//  WJWebViewController.m
//  BeDeJie
//
//  Created by jerry on 2017/1/29.
//  Copyright © 2017年 jerry. All rights reserved.
//

#import "WJWebViewController.h"
#import <WebKit/WebKit.h>

@interface WJWebViewController ()

@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *refreshBtn;

@property (nonatomic, weak) WKWebView *webView;

@end

@implementation WJWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置背景色
    self.view.backgroundColor = WJColor(206, 206, 206);
    
    //添加WKWebView
    WKWebView *webview = [[WKWebView alloc] init];
    self.webView = webview;
    [self.contentView addSubview:webview];
    
    //展示网页
    NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
    [webview loadRequest:request];
    
    //KVO监听属性改化
    /*
        Observer:观察者
     　 KeyPath:观察webview哪个属性
        option:NSKeyValueObservingOptionNew,观察新值改变
     
     　  注意：KVO一定要移除
     */
    [webview addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webview addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    [webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [webview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
}

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    self.backBtn.enabled = self.webView.canGoBack;
    self.forwardBtn.enabled = self.webView.canGoForward;
    self.progressView.progress = self.webView.estimatedProgress;
    self.progressView.hidden = self.webView.estimatedProgress >= 1;
    self.title = self.webView.title;
    
}

#pragma mark - 对象被销毁
- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"canGoForward"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    _webView.frame = self.contentView.bounds;
}

- (IBAction)goBack:(UIBarButtonItem *)sender {
    [self.webView goBack];
}

- (IBAction)goForward:(UIBarButtonItem *)sender {
    [self.webView goForward];
}

- (IBAction)goRefresh:(UIBarButtonItem *)sender {
    [self.webView reload];
}

@end
